﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//
using DHNetSDK;
using Utility;
using System.Runtime.InteropServices;
using DLLTest.OpertionClass;

namespace DLLTest
{
    public partial class frm_RecordDownload : Form
    {
        //
        /// <summary>
        /// 程序消息提示Title
        /// </summary>
        private const string pMsgTitle = "网络文件下载程序";
        /// <summary>
        /// 最后操作信息显示格式
        /// </summary>
        private const string pErrInfoFormatStyle = "代码:errcode;\n描述:errmSG.";
        /// <summary>
        /// 用户信息
        /// </summary>
        private USER_MANAGE_INFO userManageInfo;
        /// <summary>
        /// 常规报警信息
        /// </summary>
        private NET_CLIENT_STATE clientState;
        /// <summary>
        /// 按文件下载句柄
        /// </summary>
        private int pDownloadHandleByFile;
        /// <summary>
        /// 按时间下载句柄
        /// </summary>
        private int pDownloadHandleByTime;
        /// <summary>
        /// 下载句柄
        /// </summary>
        private int pDownloadHandle;
        /// <summary>
        /// 断开回调
        /// </summary>
        private fDisConnect disConnect;
        /// <summary>
        /// 下载回调
        /// </summary>
        private fDownLoadPosCallBack downLoadFun;

        //private fTimeDownLoadPosCallBack timeDownLoadFun;
        /// <summary>
        /// 下载进度百分比
        /// </summary>
        private double dblDownLoadPos;

        private delegate void fSetProgressPos(int lPlayHandle, UInt32 dwTotalSize, UInt32 dwDownLoadSize);

        private fSetProgressPos setProgressPos;

        //private string strUserName = "guset";

        private NET_DEVICEINFO deviceInfo;
        //
        public frm_RecordDownload()
        {            
            InitializeComponent();
            
        }

        /// <summary>
        /// 按文件下载按钮按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownLoad1_Click(object sender, EventArgs e)
        {
            frm_PlayBackByFileSet fpf = new frm_PlayBackByFileSet();
            int pPlayBackChanneID=0;
            NET_RECORDFILE_INFO fileInfo;
            if (PanelOpertion.SelectedPanel == null)
            {        
                return;                
            }
            if (txtDirPath1.Text == "")
            {
                //此处需要判断是否选择了正确的盘符,用split分割
                btnDirSelect1.PerformClick();
                //MessageBox.Show("请选择保存路径");
            }
            if (txtFileName1.Text == "")
            {
                MessageBox.Show("请输入文件名");
                //此处需要判断是否选择了正确的盘符
                return;
            }
            if (PanelOpertion.SelectedPanel.Tag != null)
            {
                #region 提取通道号,取出正在播放的通道号
                string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
                fpf.txtDevName.Text = panUD[0].ToString();//保存文件名,以ip地址开头
                fpf.gLoginID = Convert.ToInt32(panUD[4].ToString());//登录pLogin                
                fpf.txtChannelID.Text = panUD[5].ToString();//通道号                   
                #endregion
                fpf.ShowDialog();
                if (fpf.blnOKEnter == true)//如果文件选项成立
                {
                    pPlayBackChanneID = Convert.ToInt32(fpf.txtChannelID.Text.Trim());//给出通道号
                    fileInfo = fpf.gFileInfo;
                    //**********按文件下载**********
                    if (txtDirPath1.Text.Trim().Length > 0 && txtFileName1.Text.Trim().Length > 0)//如果路径及文件名不为空
                    {
                        string strFileName = txtFileName1.Text;
                        strFileName = strFileName.ToLower();
                        if (!strFileName.EndsWith(".dav"))
                            strFileName += ".dav";
                        pDownloadHandleByFile = DHClient.DHDownloadByRecordFile(fpf.gLoginID, fileInfo, txtDirPath1.Text + @"\" + strFileName, downLoadFun, IntPtr.Zero);
                        if (pDownloadHandleByFile != 0)
                        {
                            btnDownLoad1.Tag = "下载中";
                            pDownloadHandle = pDownloadHandleByFile;
                            btnDownLoad2.Enabled = false;
                            btnDownLoad1.Enabled = false;
                            btnStopDownLoad1.Enabled = true;
                            MessageUtil.ShowMsgBox(StringUtil.ConvertString("开始下载!"),
                                                   StringUtil.ConvertString(pMsgTitle));
                        }
                        else
                        {
                            MessageUtil.ShowMsgBox(StringUtil.ConvertString(DHClient.LastOperationInfo.errMessage, "ErrorMessage"),
                                                   StringUtil.ConvertString(pMsgTitle));
                        }
                    }
                    else
                    {
                        MessageUtil.ShowMsgBox(StringUtil.ConvertString("请输入有效的录像保存目录和文件名!"),
                                      StringUtil.ConvertString(pMsgTitle));
                    }
                    //****************
                }
            }
            else
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("请选择正在播放的通道后在选择下载!"),
                                  StringUtil.ConvertString(pMsgTitle));
                this.Close();
            }
        }
        private void DownloadProgress(int lPlayHandle, UInt32 dwTotalSize, UInt32 dwDownLoadSize)
        {

            if (dwDownLoadSize != 0xFFFFFFFF &&
                dwDownLoadSize != 0xFFFFFFFE &&
                dwDownLoadSize <= dwTotalSize)
            {
                int iPos = (int)((dwDownLoadSize * 100) / dwTotalSize);
                Console.WriteLine(iPos.ToString() + " " + dwDownLoadSize.ToString() + "/" + dwTotalSize.ToString());
                psbMain.Value = iPos;
            }
            else
            {
                if (0xFFFFFFFF == dwDownLoadSize)
                {
                    btnDownLoad2.Tag = "";
                    psbMain.Value = 0;
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString("下载结束！"));
                    btnDownLoad1.Enabled = true;
                    btnDownLoad2.Enabled = true;

                    psbMain.Value = 0;

                    //DHClient.DHStopDownload(lPlayHandle);
                }
                else if (0xFFFFFFFE == dwDownLoadSize)
                {
                    btnDownLoad2.Tag = "";
                    psbMain.Value = 0;
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString("磁盘空间不足！"));
                    btnDownLoad1.Enabled = true;
                    btnDownLoad2.Enabled = true;

                    psbMain.Value = 0;

                    //DHClient.DHStopDownload(lPlayHandle);
                }
            }
        }
        /// <summary>
        /// 下载回调
        /// </summary>
        /// <param name="lPlayHandle">播放句柄</param>
        /// <param name="dwTotalSize">累计大小</param>
        /// <param name="dwDownLoadSize">下载大小</param>
        /// <param name="dwUser">用户数据</param>
        private void DownLoadPosFun(int lPlayHandle, UInt32 dwTotalSize, UInt32 dwDownLoadSize, IntPtr dwUser)
        {
            this.Invoke(setProgressPos, new object[] { lPlayHandle, dwTotalSize, dwDownLoadSize });

            if (0xFFFFFFFF == dwDownLoadSize || 0xFFFFFFFE == dwDownLoadSize)
            {
                DHClient.DHStopDownload(lPlayHandle);
            }
        }

        //private void TimeDownLoadPosFun(int lPlayHandle, UInt32 dwTotalSize, UInt32 dwDownLoadSize, int index, NET_RECORDFILE_INFO recordfileinfo, IntPtr dwUser)
        //private void TimeDownLoadPosFun(int lPlayHandle, UInt32 dwTotalSize, UInt32 dwDownLoadSize, IntPtr dwUser)
        public void TimeDownLoadPosFun(int lPlayHandle, int dwTotalSize, int dwDownLoadSize, int index
            , NET_RECORDFILE_INFO recordfileinfo, IntPtr dwUser)
        {
            this.Invoke(setProgressPos, new object[] { lPlayHandle, (UInt32)dwTotalSize, (UInt32)dwDownLoadSize });

            if (0xFFFFFFFF == dwDownLoadSize || 0xFFFFFFFE == dwDownLoadSize)
            {
                DHClient.DHStopDownload(lPlayHandle);
            }
        }
      
        /// <summary>
        /// 停止按文件下载按钮按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopDownLoad1_Click(object sender, EventArgs e)
        {
            if (btnDownLoad1.Tag.ToString().Equals("下载中"))
            {
                bool blnStopSucced = DHClient.DHStopDownload(pDownloadHandleByFile);
                if (blnStopSucced)
                {
                    btnDownLoad1.Enabled = true;
                    btnDownLoad2.Enabled = true;
                    btnStopDownLoad1.Enabled = false;

                    MessageUtil.ShowMsgBox(StringUtil.ConvertString("停止下载成功！"),
                                           StringUtil.ConvertString(pMsgTitle));
                }
                else
                {
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString(DHClient.LastOperationInfo.errMessage, "ErrorMessage"),
                                           StringUtil.ConvertString(pMsgTitle));
                }
                btnDownLoad1.Tag = "";
                psbMain.Maximum = 100;
                psbMain.Value = 0;
            }
            else
            {
                //MessageUtil.ShowMsgBox(StringUtil.ConvertString("当前没有下载任务!"),
                //                       StringUtil.ConvertString(pMsgTitle));
            }
        }

        /// <summary>
        /// 获取按文件下载的下载进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetDownLoadPos1_Click(object sender, EventArgs e)
        {
            if (btnDownLoad1.Tag.ToString().Equals("下载中"))
            {
                int dwTotal = 0;
                int dwSize = 0;
                bool blnGetPosSucced = DHClient.DHGetDownloadPos(pDownloadHandleByFile, out dwTotal, out dwSize);
                if (blnGetPosSucced)
                {
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString("下载统计:") + "\n\t" +
                                           StringUtil.ConvertString("总长度:") +
                                           dwTotal.ToString() + "\n\t" + StringUtil.ConvertString("己下载:") + dwSize.ToString(),
                                           StringUtil.ConvertString(pMsgTitle));
                }
                else
                {
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString(DHClient.LastOperationInfo.errMessage, "ErrorMessage"),
                                           StringUtil.ConvertString(pMsgTitle));
                }
            }
            else
            {
                //MessageUtil.ShowMsgBox(StringUtil.ConvertString("当前没有下载任务!"),
                //                       StringUtil.ConvertString(pMsgTitle));
            }
        }

       
        private void btnDirSelect_Click(object sender, EventArgs e)
        {
            if (fbdMain.ShowDialog() == DialogResult.OK)
            {
                txtDirPath2.Text = fbdMain.SelectedPath;
            }
        }
        /// <summary>
        /// 按文件下载目录选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDirSelect1_Click(object sender, EventArgs e)
        {
            if (fbdMain.ShowDialog() == DialogResult.OK)
            {
                txtDirPath1.Text = fbdMain.SelectedPath;
            }
        }       
    }
}
